package com.jsgt.greekfire.ui.main


import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.AppConfig
import com.fhx.core.base.BaseActivity
import com.fhx.core.goToActivity
import com.fhx.core.utils.NetworkUtil
import com.fhx.core.utils.ToastUtils
import com.jsgt.greekfire.LOGIN_STATUS
import com.jsgt.greekfire.R
import com.jsgt.greekfire.event.LoginEvent
import com.jsgt.greekfire.event.NetChangeEvent
import com.jsgt.greekfire.factory.UserViewModelFactory
import com.jsgt.greekfire.ui.home.HomeFragment
import com.jsgt.greekfire.ui.home.entrance.EntranceActivity
import com.jsgt.greekfire.ui.main.adapter.FragmentAdapter
import com.jsgt.greekfire.ui.main.updatedialog.UpdateDialogFragment
import com.jsgt.greekfire.ui.mine.MineFragment
import com.jsgt.greekfire.ui.pool.PoolFragment
import com.jsgt.greekfire.ui.trading.TradingFragment
import com.jsgt.greekfire.viewmodel.UserViewModel
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


@Deprecated("这个类开始会初始化所有的Fragment")
class MainActivity : BaseActivity() {
    private val userViewModel: UserViewModel by lazy {
        ViewModelProvider(
            this,
            UserViewModelFactory()
        ).get(UserViewModel::class.java)
    }
    private val poolFragment by lazy { PoolFragment() }
    private val homeFragment by lazy { HomeFragment() }
//    private val marketFragment by lazy { MarketFragment() }
    private val assetsFragment by lazy { MineFragment() }
    override fun getLayoutId(): Int = R.layout.activity_main
    var updateDialogFragment: UpdateDialogFragment? = null
    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        main_tab_group.resetState()
        main_view_pager.currentItem = 0

//        marketFragment.loadAll()
        assetsFragment.loadData()
        poolFragment.resetData()
        setLoginState(LOGIN_STATUS)
    }

    override fun main() {

        AppConfig.getVersion()

//        initrongyun()
        initPage()
        userViewModel.versionUpdateLiveData.observe(this, Observer {
            if (updateDialogFragment == null) {
                if (it?.Android != null && !TextUtils.isEmpty(it.Android!!.version)) {
                    checkVersion = true
                    if (AppConfig.getVersion()!! < it.Android!!.version!!) {
                        val bundle = Bundle()
                        bundle.putParcelable("bean", it)
                        updateDialogFragment = UpdateDialogFragment()
                        updateDialogFragment!!.arguments = bundle
                        updateDialogFragment!!.show(supportFragmentManager, "updateFragment")
                    }
                }
            }

        })
        setLoginState(LOGIN_STATUS)
    }

    var checkVersion = false//是否检测过版本
    override fun onResume() {
        super.onResume()
        if (!checkVersion) {
            userViewModel.getAppVersion()
        }
    }

    /**
     * 设置是否已创建/导入钱包
     */
    fun setLoginState(isLogin: Boolean) {
        main_tab_group.setLoginState(isLogin)
    }

    /**
     * 加载底部fragment
     */
    private fun initPage() {
        val fragments = arrayListOf<Fragment>()
        fragments.add(homeFragment)
//        fragments.add(marketFragment)
        fragments.add(poolFragment)
        fragments.add(TradingFragment())
        fragments.add(assetsFragment)
        main_view_pager.adapter =
            FragmentAdapter(
                supportFragmentManager,
                fragments
            )
        main_view_pager.offscreenPageLimit = 3
        main_tab_group.setViewPager(main_view_pager)
        main_tab_group.loginClick = { EntranceActivity.start(this) }
        /*main_tab_group.setClickCallback(object : TabButtonGroup.ClickCallback {
            override fun result() {
                EntranceActivity.start(this@MainActivity)
            }
        })*/
    }

    private var mLastClickBackTime //上次点击back键的时间
            : Long = 0

    override fun onBackPressed() {
        val curTime = System.currentTimeMillis()
        if (curTime - mLastClickBackTime > 2000) {
            mLastClickBackTime = curTime
            ToastUtils.show(this, getString(R.string.try_again_exit))
            return
        }
        super.onBackPressed()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onLoginEvent(e: LoginEvent) {
        ToastUtils.show(this, e.msg!!)
        setLoginState(false)
        goToActivity<MainActivity>()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onNetChangeEvent(e: NetChangeEvent) {
        if (NetworkUtil.isNetworkAvailable()) {
            if (!checkVersion) {
                userViewModel.getAppVersion()
            }
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)//不实现这个方法，系统恢复activity时不会出错
    }


    fun initrongyun() {

//        RongIM.connect("123465789kjg", object : ConnectCallback() {
//            override fun onTokenIncorrect() {}
//            override fun onSuccess(userid: String) {
//                Log.e("TAG", "--onSuccess$userid")
//            }
//
//            override fun onError(errorCode: RongIMClient.ErrorCode) {
//                Log.e("TAG", "--onSuccess$errorCode")
//            }
//        })

    }

}
